
local unit_attribute = require 'types.unit_attribute'
local attribute = unit_attribute.field

local all_data = {}
local save_data = {}

--[解析属性]
function cd_unpack_attrs(text,key)
    local fmt = ('(.*)+\'(%s[0-9])\''):format(key)
    local strs = split_string(text,',')
    local data = {}
    for a,s in ipairs(strs) do
        local k,v = s:match(fmt)
        if k and v then
            if attribute[k]==nil then
                log.error('错误属性注册',k)
            end
            data[a] = {k,v}
        end
    end
    if #data==0 then
        log.error('存档装备空属性')
    end
    return data
end

--增加属性
function load_cdsx(hero,item,name)
    local list = item[name]
    for a,da in ipairs(list) do
        local name = da[1]
        local key = da[2]
        local num = item[key]
        hero:add(name,num)
    end
end

function set_dz_data(key,data)
    save_data[key] = data
end

function get_dz_data(key)
    return save_data[key]
end




--整理存档数据为一个表防止卡
function get_file_data(data)
    local list = {}
    for _,da in ipairs(ac.attribute) do
        local name = da.name
		list[name] = 0
        for _,v in ipairs(data) do
            list[name] = list[name] + (v[name] or 0)
        end
	end
    return list
end

ac.game:event '英雄-加载存档数据'(function(_,hero)
    local player = hero.owner
    local data1 = player:get_data('存档属性表') or {}
    local data2 = player:get_data('存档函数表') or {}
    LoadItemSX(hero,data1,1,true)
    for _,fun in ipairs(data2) do
        fun(hero)
    end
    player:notify('玩家-刷新UI',player)
end)

ac.game:event '同步-装扮模型'(function(_,player,model,ref)
    local hero = player.hero
    if hero and model and ref then
        local path = '装扮模型'..ref
        local effect = hero:get_data(path)
        if effect then
            effect:remove()
        end
        if not effect or model~=effect.model then
            hero:set_data(path,hero:add_effect(ref,model))
        end
    end
end)


local load = function(player)
    local count = player:get_data('等待存档',0) + 1
    player:set_data('等待存档',count)
    if count==2 then
        local attrs = {}
        local events = {}
        local hero = player.hero
        player:notify('玩家-读取存档',player,attrs,events)
        player:set_data('存档属性表',get_file_data(attrs))
        player:set_data('存档函数表',events)
        if hero then
            hero:notify('英雄-加载存档数据',hero)
        end
    end
end

ac.game:event '玩家-官方存档读取完毕'(function(_,player)
    player:notify('玩家-存档读取前',player)
    load(player)
end)

--拉去服务器数据，超过4秒不处理
local trg = ac.game:event '游戏-服务器初始化'(function()
    ac.each_player(function(player)
        load(player)
    end)
end)
ac.wait(4000,function()
    trg:remove()
    ac.each_player(function(player)
        load(player)
    end)
end)